﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.IO;

namespace HiStaff.Control
{
    [ToolboxBitmap(typeof(PictureBox))]
    public class HiImageBox : PictureBox
    {
        private bool _readOnly = false;
        private bool _readOnlyWhenEdit = false;
        bool _isRequire = false;
        public bool IsRequire { get { return _isRequire; } set { _isRequire = value; } }
        public bool ReadOnly { get { return _readOnly; } set { _readOnly = value; } }
        public bool ReadOnlyWhenEdit { get { return _readOnlyWhenEdit; } set { _readOnlyWhenEdit = value; } }
        public string DataField { get; set; }
        public object ImageData
        {
            get
            {
                try
                {
                    MemoryStream streamImg;
                    if (this.Image != null)
                    {
                        streamImg = new MemoryStream();
                        this.Image.Save(streamImg, ImageFormat.Jpeg);
                        return streamImg;
                    }
                    return null;
                }
                catch
                {
                    return null;
                }
            }
            set
            {
                if (value != null)
                {
                    MemoryStream streamImg;
                    if (value is MemoryStream)
                    {
                        streamImg = ((MemoryStream)value);
                    }
                    else
                    {
                        streamImg = new MemoryStream((byte[])value);
                    }
                    this.Image = System.Drawing.Image.FromStream(streamImg);
                }
                else
                {
                    this.Image = null;
                }
            }
        }
        public HiImageBox()
        {
            this.DoubleClick += new EventHandler(HiImageBox_DoubleClick);
            this.ErrorImage = null;
        }
        private void HiImageBox_DoubleClick(object sender, EventArgs e)
        {
            if (!_readOnly)
            {
                var ofDlg = new OpenFileDialog();
                ofDlg.Filter = "Image file|*.jpg,*.png";
                ofDlg.ShowDialog();
                var filename = ofDlg.FileName;
                if (!string.IsNullOrEmpty(filename))
                {
                    ImageData = File.ReadAllBytes(filename);
                }
            }
        }
    }
}
